/************************************************************************

								Heroes IV
					  Copyright 2000, The 3DO Company

	------------------------------------------------------------------
  							 script_give_spell.cpp

	$Header: /heroes4/script_give_spell.cpp $

	$NoKeywords: $

 ************************************************************************/

// kill the 255+ character identifier warning.  Templates tend to exceed that easily.
#include "precompiled.h"
#pragma warning( disable: 4786 )

#include "script_give_spell.h"

#include "sized_int_types.h"
#include "spell_properties.h"
#include "streambuf_operators.h"
#include "basic_dialog.h"
#include "script_targeting.h"
#include "hero.h"

namespace {
	static bool g_mute_icons = false;
};

// --------------------------------------------------------------------------
// t_script_give_spell members
// --------------------------------------------------------------------------

// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
bool t_script_give_spell::read_from_map(
	std::streambuf &	stream,
	int					format_version )
{
	if ( !t_script_targeted_action< t_target >::read_from_map( stream, format_version ) )
		return false;

	m_spell = t_spell( get< t_uint16 >( stream ) );
	return m_spell >= 0 && m_spell < k_spell_count && is_teachable( m_spell );
}

bool t_script_give_spell::read( std::streambuf& stream, int version )
{
	if ( !t_script_targeted_action< t_target >::read( stream, version ) )
		return false;

	m_spell = get< t_spell >( stream );
	return m_spell >= 0 && m_spell < k_spell_count;
}

bool t_script_give_spell::write( std::streambuf& stream ) const
{
	if ( !t_script_targeted_action< t_target >::write( stream ) )
		return false;

	put< t_spell >( stream, m_spell );

	return true;
}

void t_script_give_spell::add_icons(t_basic_dialog* dialog) const
{
	if (g_mute_icons == false)
		dialog->add_spell(get_spell());
}

void t_script_give_spell::do_action(t_hero* hero) const
{
	g_mute_icons = true;
	
	if ( (hero == NULL) || (hero->in_spellbook(get_spell())) )
		return;

	g_mute_icons = !hero->learn_spell(get_spell());
}
